package com;

import javax.lang.model.type.ErrorType;
import java.io.*;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;

import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by IntelliJ IDEA.
 * User: BGONZ8
 * Date: 9/24/11
 * Time: 10:15 AM
 * To change this template use File | Settings | File Templates.
 */
public class util {

    static int val1 = 11110;

    static String  getRandomTransactionID() throws Exception
    {
        Random ran = new Random();
        int rnd = ran.nextInt(9999) + 578;
        String rndId = "abc" + getNextID();
        return rndId;
    }

    static String getToday1()
    {
        Calendar cal = Calendar.getInstance();
        cal.set( Calendar.HOUR_OF_DAY, 0 );
        cal.set( Calendar.MINUTE, 0 );
        cal.set( Calendar.SECOND, 0 );
        cal.set( Calendar.MILLISECOND, 0 );
        return( cal.getTime().toString() );
    }


    /**
    * Sends an HTTP GET request to a url
    *
    * @param endpoint - The URL of the server. (Example: " http://www.yahoo.com/search")
    * @param requestParameters - all the request parameters (Example: "param1=val1&param2=val2"). Note: This method will add the question mark (?) to the request - DO NOT add it yourself
    * @return - The response from the end point
    */
    public static String sendGetRequest(String endpoint, String requestParameters)  throws Exception
    {
        String result = null;
        if (endpoint.startsWith("http://"))
        {
            // Send a GET request to the servlet
            try
            {
                // Send data
                String urlStr = endpoint;
                if (requestParameters != null && requestParameters.length () > 0)
                {
                    urlStr += "?" + requestParameters;
                }
                URL url = new URL(urlStr);
                URLConnection conn = url.openConnection ();
                // Get the response
                BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuffer sb = new StringBuffer();
                String line;
                while ((line = rd.readLine()) != null)
                {
                    sb.append(line);
                }
                rd.close();
                result = sb.toString();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
    * Reads data from the data reader and posts it to a server via POST request.
    * data - The data you want to send
    * endpoint - The server's address
    * output - writes the server's response to output
    * @throws Exception
    */
    public static void postData(Reader data, URL endpoint, Writer output) throws Exception
    {
        HttpURLConnection urlc = null;
        try
        {
                urlc = (HttpURLConnection) endpoint.openConnection();
            try
            {
            urlc.setRequestMethod("POST");
            }
            catch (ProtocolException e)
            {
                throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
            }
            urlc.setDoOutput(true);
            urlc.setDoInput(true);
            urlc.setUseCaches(false);
            urlc.setAllowUserInteraction(false);
            urlc.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");
            OutputStream out = urlc.getOutputStream();
            try
            {
                Writer writer = new OutputStreamWriter(out, "UTF-8");
                pipe(data, writer);
                writer.close();
            }
            catch (IOException e)
            {
                throw new Exception("IOException while posting data", e);
            }
            finally
            {
                if (out != null)
                    out.close();
            }
            InputStream in = urlc.getInputStream();
            try
            {
                Reader reader = new InputStreamReader(in);
                pipe(reader, output);
                reader.close();
            }
            catch (IOException e)
            {
                throw new Exception("IOException while reading response", e);
            }
            finally
            {
                if (in != null)
                in.close();
            }
        }
        catch (IOException e)
        {
            throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e);
        } finally
        {
        if (urlc != null)
            urlc.disconnect();
        }
    }

    /**
    * Pipes everything from the reader to the writer via a buffer
    */
    private static void pipe(Reader reader, Writer writer) throws IOException
    {
        char[] buf = new char[1024];
        int read = 0;
        while ((read = reader.read(buf)) >= 0)
        {
            writer.write(buf, 0, read);
        }
        writer.flush();
    }

    public static List<String> getSourceSystems()   throws Exception
    {
        ArrayList<String> srcs = new ArrayList<String>();
        DB db = new DB();
        ResultSet rset = db.execute("select SRC_SYS_CD from SRC_SYS");
        while (rset.next() )
        {
            srcs.add(rset.getString("SRC_SYS_CD"))  ;
        }
        db.close();
        return srcs;
    }

    public static String getNextID()   throws Exception
    {
        DB db = new DB();
        String ret = "1";
        ResultSet rset = db.execute("select ALOTMT_DTL_SEQ.NEXTVAL as nextval from dual");
        while (rset.next() )
        {
            ret = rset.getString("nextval") ;
        }
        return ret;
    }

    public static String getNextNum()
    {
        val1++;
        return String.valueOf(val1);
    }

    public static void say(String it)
    {
        System.out.println(it);
    }

} // end class



/*
        http://www.aviransplace.com/2008/01/08/make-http-post-or-get-request-from-java/
        String file_name = “result.html”;

        URL formAction = new URL(”http://192.168.1.1/target_path”);
        FileWriter fw = new FileWriter(file_name);
        postData(new StringReader(xml_data), formAction, fw);

        ===

        new StringReader(”type=1&keyword=abc”)
 */